<template>
  <view class="member-list-page">
    <!-- 导航栏 -->
    <tn-nav-bar fixed alpha customBack>
      <view slot="back" class='tn-custom-nav-bar__back' @click="goBack">
        <text class='icon tn-icon-left'></text>
      </view>
      <text class="nav-title"></text>
    </tn-nav-bar>
    
    <!-- 顶部标题 -->
    <view class="page-header">
      <view class="header-title">会员名单</view>
    </view>

    <!-- 筛选器 -->
    <view class="filter-section">
      <!-- 城市选择 -->
      <view class="filter-item">
        <view class="filter-label">城市:</view>
        <!-- 城市选择 -->
        <picker mode="selector" :range="cityNames" @change="onCityChange" :value="currentRegion">
          <view class="filter-picker filter-picker-city">
            <text class="picker-text">{{ currentCityName }}</text>
            <text class="tn-icon-down-triangle picker-icon"></text>
          </view>
        </picker>
      </view>

      <!-- 届别筛选 -->
      <view class="filter-item">
        <view class="filter-label">届别:</view>
        <picker mode="selector" :range="gradeOptions" @change="onGradeChange" :value="selectedGradeIndex">
          <view class="filter-picker">
            <text class="picker-text">{{ selectedGradeIndex === 0 ? '全部' : gradeOptions[selectedGradeIndex] }}</text>
            <text class="tn-icon-down-triangle picker-icon"></text>
          </view>
        </picker>
      </view>
      
      <!-- 专业筛选 -->
      <view class="filter-item">
        <view class="filter-label">专业:</view>
        <picker mode="selector" :range="majorOptions" @change="onMajorChange" :value="selectedMajorIndex">
          <view class="filter-picker">
            <text class="picker-text">{{ selectedMajorIndex === 0 ? '全部' : majorOptions[selectedMajorIndex] }}</text>
            <text class="tn-icon-down-triangle picker-icon"></text>
          </view>
        </picker>
      </view>
    </view>

    <!-- 会员列表 -->
    <view class="member-container">
      <view class="member-count">
        共 {{ filteredMembers.length }} 名会员
      </view>

      <!-- 表格 -->
      <view class="member-table">
        <!-- 表头 -->
        <view class="table-header">
          <view class="table-cell cell-name">姓名</view>
          <view class="table-cell cell-class">届别</view>
          <view class="table-cell cell-major">专业</view>
          <view class="table-cell cell-phone">联系方式</view>
        </view>

        <!-- 表格内容 -->
        <view class="table-body">
          <view 
            v-for="(member, index) in filteredMembers" 
            :key="index"
            class="table-row"
          >
            <view class="table-cell cell-name">
              <view class="name-text">{{ member.name }}</view>
            </view>
            <view class="table-cell cell-class">{{ member.grade }}</view>
            <view class="table-cell cell-major">{{ member.major }}</view>
            <view class="table-cell cell-phone">
              <view class="phone-text" @click="callPhone(member.phone)">
                {{ maskPhone(member.phone) }}
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-if="filteredMembers.length === 0" class="empty-state">
        <view class="empty-icon">📋</view>
        <view class="empty-text">暂无符合条件的会员</view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'MemberList',
  data() {
    return {
      currentRegion: 0,
      selectedGradeIndex: 0,
      selectedMajorIndex: 0,
      gradeOptions: ['全部', '2017届', '2018届', '2019届', '2020届', '2021届', '2022届', '2023届', '2024届', '2025届'],
      majorOptions: ['全部'],
      // 不再硬编码 regions.members
      rawMembers: [], // 存储从后端获取的原始用户
      allCities: ['全部', '北京', '上海', '广州', '深圳', '杭州', '成都', '武汉', '西安', '长春', '南京', '重庆', '天津'], // 假城市池
    }
  },
  onLoad() {
    this.loadMemberList()
  },
  methods: {
    // 使用 uni.request 获取会员列表（微信小程序兼容）
    loadMemberList() {
      // 获取 token
      const token = uni.getStorageSync('token') || ''
      
      uni.request({
        url: 'http://localhost:8080/app/users/listAllUser',
        method: 'GET',
        header: {
          'Content-Type': 'application/json',
          'Authorization': token ? `Bearer ${token}` : ''
        },
        success: (res) => {
          console.log('获取会员列表成功', res)
          if (res.statusCode === 200 && res.data.code === 200) {
            this.rawMembers = res.data.rows.map(user => {
              // 映射为前端需要的字段
              const graduationYear = user.graduationYear || new Date().getFullYear();
              const grade = graduationYear ? `${graduationYear}届` : '未知届';
              const major = user.major || '未填写';
              const name = user.realName || user.username || '匿名';
              const phone = user.phone || '';
      
              // 👇 假城市分配逻辑（可根据 company / college / 随机）
              let city = '北京'; // 默认
              if (user.company) {
                if (user.company.includes('阿里') || user.company.includes('淘宝') || user.company.includes('蚂蚁')) city = '杭州';
                else if (user.company.includes('腾讯') || user.company.includes('微信')) city = '深圳';
                else if (user.company.includes('华为') || user.company.includes('中兴')) city = '深圳';
                else if (user.company.includes('百度') || user.company.includes('字节')) city = '北京';
                else if (user.company.includes('银行') || user.company.includes('金融')) city = '上海';
                else city = this.allCities[Math.floor(Math.random() * (this.allCities.length - 1)) + 1];
              } else if (user.college) {
                // 学院映射（示例）
                if (user.college.includes('计算机') || user.college.includes('软件')) city = '杭州';
                else if (user.college.includes('经济') || user.college.includes('管理')) city = '上海';
                else city = '北京';
              }
              return {
                name,
                grade,
                major,
                phone,
                city,
                original: user // 保留原始数据备用
              };
            });
      
            // 动态生成专业选项（去重）
            const majors = [...new Set(this.rawMembers.map(m => m.major))];
            this.majorOptions = ['全部', ...majors];
          } else {
            uni.showToast({ 
              title: res.data.msg || '获取会员列表失败', 
              icon: 'none' 
            });
          }
        },
        fail: (err) => {
          console.error('获取会员列表失败', err);
          uni.showToast({ 
            title: '网络请求失败，请检查网络连接', 
            icon: 'none' 
          });
        }
      })
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack({
        delta: 1
      })
    },
    
    // 城市选择改变
    onCityChange(e) {
      this.currentRegion = e.detail.value
      this.resetFilter()
    },
    
    // 届别筛选改变
    onGradeChange(e) {
      this.selectedGradeIndex = e.detail.value
    },
    
    // 专业筛选改变
    onMajorChange(e) {
      this.selectedMajorIndex = e.detail.value
    },
    
    // 重置筛选
    resetFilter() {
      this.selectedGradeIndex = 0
      this.selectedMajorIndex = 0
    },
    
    // 拨打电话
    callPhone(phone) {
      // 这里可以实现拨打电话功能
      uni.showModal({
        title: '联系方式',
        content: phone,
        showCancel: false
      })
      
      // 如果需要实际拨打电话，可以使用：
      // uni.makePhoneCall({
      //   phoneNumber: phone
      // })
    },

    maskPhone(phone) {
      if (!phone) return ''
      const str = String(phone)
      if (str.length <= 7) {
        return str.replace(/(\d{3})\d+/, '$1****')
      }
      const prefix = str.slice(0, 3)
      const suffix = str.slice(-4)
      return `${prefix}****${suffix}`
    }
  },
  computed: {
    // 动态城市列表：全部 + 所有出现过的城市（去重）
    cityNames() {
      const cities = [...new Set(this.rawMembers.map(m => m.city))];
      return ['全部', ...cities];
    },
  
    // 当前选中的城市名（用于显示）
    currentCityName() {
      return this.cityNames[this.currentRegion] || '全部';
    },
  
    // 筛选后的成员
    filteredMembers() {
      let list = [...this.rawMembers];
  
      // 城市筛选
      if (this.currentRegion !== 0) {
        const selectedCity = this.cityNames[this.currentRegion];
        list = list.filter(m => m.city === selectedCity);
      }
  
      // 届别筛选
      if (this.selectedGradeIndex !== 0) {
        const grade = this.gradeOptions[this.selectedGradeIndex];
        list = list.filter(m => m.grade === grade);
      }
  
      // 专业筛选
      if (this.selectedMajorIndex !== 0) {
        const major = this.majorOptions[this.selectedMajorIndex];
        list = list.filter(m => m.major === major);
      }
	  console.log(list)
      return list;
    }
  }
}
</script>

<style lang="scss" scoped>
.member-list-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 40rpx;
}

/* 导航栏样式 */
.nav-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #FFFFFF;
}

/* 自定义导航栏返回按钮样式 */
.tn-custom-nav-bar__back {
  width: 60%;
  height: 100%;
  position: relative;
  display: flex;
  justify-content: space-evenly;
  align-items: center;
  box-sizing: border-box;
  background-color: rgba(0, 0, 0, 0.15);
  border-radius: 1000rpx;
  border: 1rpx solid rgba(255, 255, 255, 0.5);
  color: #FFFFFF;
  font-size: 18px;
  
  .icon {
    display: block;
    flex: 1;
    margin: auto;
    text-align: center;
  }
}

/* 顶部标题样式 */
.page-header {
  padding: 20rpx 20rpx;
  text-align: center;
  color: black;
  margin-top: 80rpx;
  margin-bottom: 20rpx; /* 调整下边距，适配小程序 */
  
  .header-title {
    font-size: 48rpx;
    font-weight: bold;
    margin-bottom: 0;
    letter-spacing: 2rpx;
  }
}


/* 筛选器 */
.filter-section {
  display: flex;
  flex-wrap: nowrap;
  align-items: center;
  background-color: white;
  margin: 20rpx 20rpx;
  padding: 12rpx 10rpx;
  border-radius: 10rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
  gap: 8rpx;
  overflow: hidden;
  box-sizing: border-box;
  
  .filter-item {
    display: flex;
    align-items: center;
    flex: 1;
    min-width: 0;
    
    .filter-label {
      font-size: 26rpx;
      color: #666;
      margin-right: 3rpx;
      white-space: nowrap;
      flex-shrink: 0;
    }
    
    .filter-picker {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 6rpx 6rpx;
      background-color: #f5f5f5;
      border-radius: 8rpx;
      font-size: 24rpx;
      color: #333;
      flex: 1;
      min-width: 0;
      
      &.filter-picker-city {
        background-color: rgba(31, 77, 75, 0.9);
        color: white;
        font-weight: 500;
      }
      
      .picker-text {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        flex: 1;
        min-width: 0;
        line-height: 1.2;
      }
      
      .picker-icon {
        margin-left: 4rpx;
        font-size: 22rpx;
        color: #999;
        flex-shrink: 0;
      }
      
      &.filter-picker-city {
        .picker-text {
          color: white;
        }
        
        .picker-icon {
          color: rgba(255, 255, 255, 0.8);
        }
      }
    }
  }
}

/* 会员容器 */
.member-container {
  margin: 20rpx 30rpx;
  
  .member-count {
    font-size: 26rpx;
    color: #666;
    margin-bottom: 20rpx;
    padding: 0 10rpx;
  }
}

/* 表格样式 */
.member-table {
  background-color: white;
  border-radius: 10rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
  
  .table-header {
    display: flex;
    background-color: #1F4D4B;
    color: white;
    font-weight: bold;
    font-size: 28rpx;
    
    .table-cell {
      padding: 25rpx 15rpx;
      text-align: center;
    }
  }
  
  .table-body {
    .table-row {
      display: flex;
      border-bottom: 1rpx solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      &:active {
        background-color: #f8f8f8;
      }
      
      .table-cell {
        padding: 30rpx 15rpx;
        font-size: 26rpx;
        color: #333;
        text-align: center;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
  
  .cell-name {
    flex: 1.2;
    
    .name-text {
      font-weight: 500;
      color: #1F4D4B;
    }
  }
  
  .cell-class {
    flex: 1;
    color: white;
  }
  
  .cell-major {
    flex: 1.5;
    color: white;
  }
  
  .cell-phone {
    flex: 1.5;
    
    .phone-text {
      color: #1F4D4B;
      text-decoration: none;
    }
  }
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 100rpx 0;
  
  .empty-icon {
    font-size: 100rpx;
    margin-bottom: 20rpx;
  }
  
  .empty-text {
    font-size: 28rpx;
    color: #999;
  }
}
</style>

